package com.yueban.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yueban.R;
import com.yueban.adapter.HomeActivitiesListAdapter;
import com.yueban.constant.HttpConstant;
import com.yueban.model.ActivityData;
import com.yueban.model.BaseResponse;
import com.yueban.model.DataHolder;
import com.yueban.model.ResultCode;
import com.yueban.net.NetWorkController;
import com.yueban.util.ImageUtils;
import com.yueban.util.SPManager;
import com.yueban.views.CircleSmartImageView;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private DataHolder dataHolder;
    private RecyclerView.Adapter adapter;
    private NetWorkController netWorkController;
    CircleSmartImageView circleImageView;
    private SPManager spManager;

    private final int LOAD_NEW = 0;
    private final int LOAD_MORE = 1;
    private int category = -1;
    private boolean justSwitch = true;

    private static final int RESULT_LOAD_IMAGE = 0x1001;
    private static final int RESULT_CAMERA_IMAGE = 0x1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        spManager = new SPManager(getApplicationContext());
        initView();
        netWorkController = new NetWorkController();
    }

    //初始化view
    private void initView() {
        //注册toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_release);
        setSupportActionBar(toolbar);
        //浮动按钮
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();*/
                startActivity(new Intent(HomeActivity.this, ReleaseActivity.class));

            }
        });
        //实现侧滑菜单
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        //setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View headerView = navigationView.getHeaderView(0);
        //显示头像
        circleImageView = (CircleSmartImageView) headerView.findViewById(R.id.circle_user_icon);
        circleImageView.refreshDrawableState();
        circleImageView.setImageUrl(HttpConstant.SERVER_URL + HttpConstant.GET_USER_ICON
                + "?userId=" + spManager.getUserId());

        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopueWindow();
            }
        });

        TextView userName = (TextView) headerView.findViewById(R.id.nav_user_name);
        userName.setText(spManager.getUserName());

        //注册swipRefreshLayout
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_main);
        //设置进度条（圈）颜色
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

        //下拉刷新动作
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(LOAD_NEW);
            }
        });
        //注册RecycleView
        recyclerView = (RecyclerView) findViewById(R.id.ryv_main);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                //如果已显示到最后一条
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    if (refreshLayout.isRefreshing()) {
                        return;
                    } else {
                        //上拉加载
                        refreshLayout.setRefreshing(true);
                        getData(LOAD_MORE);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
        dataHolder = new DataHolder();
        //适配器绑定数据对象
        adapter = new HomeActivitiesListAdapter(dataHolder);
        //绑定适配器
        recyclerView.setAdapter(adapter);

        //自动刷新一次
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                //开启刷新进度条，将会在getData（）后关闭
                refreshLayout.setRefreshing(true);
                getData(LOAD_NEW);
            }
        });

    }


    private void getData(final int purpose) {
        long lastActivityId = 0;
        List<ActivityData> activityDatas = dataHolder.getActivityDatas();
        if (activityDatas != null && activityDatas.size() > 0) {
            if (purpose == LOAD_NEW) {
                activityDatas.clear();
            } else {
                lastActivityId = activityDatas.get(activityDatas.size() - 1).getId();
            }
        }
        //联网获取数据
        netWorkController.getActivities(category + "", lastActivityId)
                .subscribe(new Observer<BaseResponse<List<ActivityData>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResponse<List<ActivityData>> baseResponse) {
                        if (ResultCode.SUCCESS == baseResponse.getStatus()) {
                            ArrayList<ActivityData> newData = (ArrayList<ActivityData>) baseResponse.getData();
                            ArrayList<ActivityData> datalist = dataHolder.getActivityDatas();

                            if (newData == null || newData.size() == 0) {
                                if (justSwitch) {
                                    adapter.notifyDataSetChanged();
                                    justSwitch = false;
                                }
                                return;
                            }
                            if (purpose == LOAD_NEW) {
                                dataHolder.setActivityDatas(newData);
                            } else {
                                datalist.addAll(newData);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.notifyDataSetChanged();
                            Toast.makeText(HomeActivity.this, baseResponse.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        adapter.notifyDataSetChanged();
                        refreshLayout.setRefreshing(false);
                        Toast.makeText(HomeActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onComplete() {
                        //关闭进度条
                        refreshLayout.setRefreshing(false);
                    }
                });
    }


    /**
     * 以下是实现侧滑菜单接口的方法
     */
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        switch (id) {
            case R.id.message_home:
                break;
            case R.id.action_settings:
                Intent intent = new Intent(HomeActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_hot) {
            category = -1;
            // Handle the camera action
        } else if (id == R.id.nav_option_1) {
            category = 0;
        } else if (id == R.id.nav_option_2) {
            category = 1;
        } else if (id == R.id.nav_option_3) {
            category = 2;
        } else if (id == R.id.nav_option_4) {
            category = 3;
        } else if (id == R.id.nav_option_5) {
            category = 4;
        } else if (id == R.id.nav_option_6) {
            category = 5;
        }
        //表示刚执行切换动作
        justSwitch = true;
        //延迟500毫秒后刷新
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                getData(LOAD_NEW);
            }
        }, 500);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //注册弹出菜单
    public void showPopueWindow() {
        View popView = View.inflate(HomeActivity.this, R.layout.popue_window_camera, null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel); //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels / 3;
        final PopupWindow popupWindow = new PopupWindow(popView, weight, height);
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, RESULT_LOAD_IMAGE);
                popupWindow.dismiss();
            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //takeCamera(RESULT_CAMERA_IMAGE);
                popupWindow.dismiss();
            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RESULT_LOAD_IMAGE && null != data) {
                Uri uri = data.getData();
                try {
                    //获取尺寸和质量压缩过的bitmap
                    Bitmap bitmap = ImageUtils.getBitmapFromUri(HomeActivity.this, uri);
                    //显示缩略图

                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    netWorkController.addUserIcon(baos.toByteArray(), spManager.getUserId())
                            .subscribe(new Observer<BaseResponse>() {
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                }

                                @Override
                                public void onNext(@NonNull BaseResponse baseResponse) {
                                    if (baseResponse.getStatus() == ResultCode.SUCCESS) {
                                        circleImageView.setImageUrl("");
                                        circleImageView.refreshDrawableState();
                                        circleImageView.setImageUrl(HttpConstant.SERVER_URL + HttpConstant.GET_USER_ICON
                                                + "?userId=" + spManager.getUserId());
                                    }
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    Toast.makeText(HomeActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                                }

                                @Override
                                public void onComplete() {
                                }
                            });
                    baos.close();
                } catch (Exception e) {
                    Toast.makeText(HomeActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                }
            } else if (requestCode == RESULT_CAMERA_IMAGE && null != data) {

            }
        }
    }
}
